from django.core.serializers.json import DjangoJSONEncoder
import os
import json
import django_filters
from main.apps.userapp import models
from main.mixins.mixins import OperatorMixins
from rest_framework import response, serializers, viewsets
from rest_framework.views import APIView
from rest_framework.decorators import action


class UserappFilter(django_filters.rest_framework.FilterSet):
    class Meta:
        model = models.Userapp
        fields = {
            "create_time": ["range"],
            "operator_name": ["in", "exact"],
        }


class UserappSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Userapp
        fields = "__all__"
        read_only_fields = ("id", "delete_time")


class SyncUserappSerializer(serializers.ModelSerializer):
    def update(self, instance, validated_data):
        fields = list(
            instance.userappfields_set.filter(delete_time__isnull=True).values()
        )
        # todo
        # names = [[["demoapp1","模型1"]]
        names = []
        for item in models.Userapp.objects.filter(delete_time__isnull=True).values():
            names.append([item["code"], item["name"]])
        names = json.dumps(names, cls=DjangoJSONEncoder)
        names = names.replace(",", "\\,")
        fields = json.dumps(fields, cls=DjangoJSONEncoder)
        fields = fields.replace(",", "\\,")

        cmd = f"""fab sync_model_file:ModelNames='{names}',ModelName={instance.code},FieldList='{fields}' """
        print("cmd:", cmd)
        os.system(cmd)
        return super().update(instance, validated_data)

    class Meta:
        model = models.Userapp
        fields = "__all__"
        read_only_fields = ("id", "delete_time")


class UserappViewSet(
    OperatorMixins,
    viewsets.ModelViewSet,
):
    """
    Userapp管理
    """

    filter_class = UserappFilter
    queryset = models.Userapp.objects.filter(delete_time__isnull=True)
    serializer_class = UserappSerializer
    ordering = ("-id",)

    def get_serializer_class(self):
        if self.action in ("sync",):
            return SyncUserappSerializer

        return self.serializer_class

    @action(methods=["put"], detail=True)
    def sync(self, request, pk, *args, **kwargs):
        """sync"""
        return super().update(request, pk, *args, **kwargs)


class UserappFieldsFilter(django_filters.rest_framework.FilterSet):
    class Meta:
        model = models.UserappFields
        fields = {
            "model_id": ["in"],
            "create_time": ["range"],
            "operator_name": ["in", "exact"],
        }


class UserappFieldsSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserappFields
        fields = "__all__"
        read_only_fields = ("id", "delete_time")


class UserappFieldsViewSet(OperatorMixins, viewsets.ModelViewSet):
    """
    UserappFields管理
    """

    filter_class = UserappFieldsFilter
    queryset = models.UserappFields.objects.filter(delete_time__isnull=True)
    serializer_class = UserappFieldsSerializer
    ordering = ("-id",)

    def get_serializer_class(self):
        return self.serializer_class


class DashboardAPIView(APIView):
    def get(self, request, *args, **kwargs):
        res = {
            "code": 0,
            "data": {
                "list": [
                    {
                        "date": "2021-01-17",
                        "loginCount": 5,
                        "registerCount": 5,
                        "userCount": 1187,
                        "showCount": 56,
                        "showUserCount": 7,
                    },
                    {
                        "date": "2021-01-18",
                        "loginCount": 9,
                        "registerCount": 7,
                        "userCount": 1194,
                        "showCount": 26,
                        "showUserCount": 9,
                    },
                    {
                        "date": "2021-01-19",
                        "loginCount": 15,
                        "registerCount": 9,
                        "userCount": 1203,
                        "showCount": 31,
                        "showUserCount": 13,
                    },
                ]
            },
        }
        return response.Response(res)


class hotConfigAPIView(APIView):
    """"""

    def get(self, request, *args, **kwargs):
        res = {
            "code": 0,
            "data": {
                "count": 5,
                "page": 1,
                "size": 50,
                "list": [
                    {
                        "id": 78,
                        "content": "df",
                        "desc": "sdfgsdf",
                        "updateTime": "2020-12-31 22:26:19",
                        "createTime": "2020-12-31 22:26:19",
                    },
                    {
                        "id": 79,
                        "content": "1",
                        "desc": "5454",
                        "updateTime": "2021-01-14 14:16:54",
                        "createTime": "2021-01-14 14:16:54",
                    },
                ],
            },
        }
        return response.Response(res)
